package com.ruoyi.web.controller.module.event;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.event.EventPatrolPoint;
import com.ruoyi.system.domain.module.event.EventPointQr;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.IEventPointQrService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.web.controller.common.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 地点二维码Controller
 *
 * @author ruoyi
 * @date 2024-08-12
 */
@Validated
@Api(value = "地点二维码控制器", tags = {"地点二维码管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/point/qr")
public class EventPointQrController extends BaseController {

    private final IEventPointQrService eventPointQrService;
	private final IEstateService estateService;

	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;


    /**
     * 查询地点二维码列表
     */
    @ApiOperation("查询地点二维码列表")
    @PreAuthorize("@ss.hasPermi('module:eventPointQr:list')")
    @GetMapping("/list")
    public TableDataInfo<EventPointQr> list(@Validated EventPointQr eventPointQr) {
		SysUser sysUser = getUser();
        QueryWrapper<EventPointQr> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if (eventPointQr.getPropertyId()!=null){
				qw.eq("property_id",eventPointQr.getPropertyId());
			}
			if (eventPointQr.getEstateId()!=null){
				qw.eq("estate_id",eventPointQr.getEstateId());
			}
		}
		if (eventPointQr.getPointName()!=null){
			qw.like("point_name",eventPointQr.getPointName());
		}
        TableDataInfo<EventPointQr> td = PageUtils.buildDataInfo(eventPointQrService.page(PageUtils.buildPage(),qw));
        List<EventPointQr> list = td.getRows();
		for (EventPointQr pointQr : list){
			Estate estate = estateService.findById(pointQr.getEstateId());
			if(estate != null){
				pointQr.setEstateName(estate.getEstateName());
			}

			if(StrUtil.isNotEmpty(pointQr.getQrCode())){
				pointQr.setQrCode(imgUrl + pointQr.getQrCode());
			}
		}
        return td;
    }

	@ApiOperation("查询地点二维码列表")
	@PreAuthorize("@ss.hasPermi('module:eventPointQr:list')")
	@GetMapping("/lists")
	public List<EventPointQr> lists(@Validated EventPointQr eventPointQr) {
		SysUser sysUser = getUser();
		QueryWrapper<EventPointQr> qw = new QueryWrapper<>();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
			if(eventPointQr.getEstateId()!=null){
				qw.eq("estate_id",eventPointQr.getEstateId());
			}
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){//小区
			qw.eq("estate_id",sysUser.getEstateId());
		} else{
			if(eventPointQr.getPropertyId()!=null){
				qw.eq("property_id",eventPointQr.getPropertyId());
			}

			if(eventPointQr.getEstateId()!=null){
				qw.eq("estate_id",eventPointQr.getEstateId());
			}
		}
		TableDataInfo<EventPointQr> td = PageUtils.buildDataInfo(eventPointQrService.page(PageUtils.buildPage(),qw));
		List<EventPointQr> list = td.getRows();
		for (EventPointQr pointQr : list){
			Estate estate = estateService.findById(pointQr);
			if(estate != null){
				pointQr.setEstateName(estate.getEstateName());
			}

			if(StrUtil.isNotEmpty(pointQr.getQrCode())){
				pointQr.setQrCode(imgUrl + pointQr.getQrCode());
			}
		}
		return list;
	}

    /**
     * 导出地点二维码列表
     */
    @ApiOperation("导出地点二维码列表")
    @PreAuthorize("@ss.hasPermi('module:eventPointQr:export')")
    @Log(title = "地点二维码", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventPointQr> export(@Validated EventPointQr eventPointQr) {
        List<EventPointQr> list = eventPointQrService.list();
        ExcelUtil<EventPointQr> util = new ExcelUtil<>(EventPointQr.class);
        return util.exportExcel(list, "地点二维码");
    }

    /**
     * 获取地点二维码详细信息
     */
    @ApiOperation("获取地点二维码详细信息")
    @PreAuthorize("@ss.hasPermi('module:eventPointQr:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventPointQr> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EventPointQr eventPointQr = eventPointQrService.getById(id);
		if(eventPointQr != null){
			Estate estate = estateService.findById(eventPointQr);
			if(estate != null){
				eventPointQr.setEstateName(estate.getEstateName());
			}
		}
        return AjaxResult.success(eventPointQr);
    }

    /**
     * 新增地点二维码
     */
    @ApiOperation("新增地点二维码")
    @PreAuthorize("@ss.hasPermi('module:eventPointQr:add')")
    @Log(title = "地点二维码", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventPointQr eventPointQr) {
		boolean bl = eventPointQrService.save(eventPointQr);
		if(bl){
			try{
				String fileName = "event_point_qr_" + eventPointQr.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/event/point?id=" + eventPointQr.getId();
				int upload_type = FileUploadUtils.TYPE_EVENT_POINT_QR;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, eventPointQr.getPointName(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				eventPointQr.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (eventPointQrService.updateById(eventPointQr)) {
				return AjaxResult.success();
			}
		}

        return toAjax(bl ? 1 : 0);
    }


	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:patrolPoint:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody EventPointQr eventPointQr) {
		if(eventPointQr.getId()!=null){
			try{
				eventPointQr = eventPointQrService.getById(eventPointQr.getId());
				String fileName = "event_point_qr_" + eventPointQr.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/event/point?id=" + eventPointQr.getId();
				int upload_type = FileUploadUtils.TYPE_EVENT_POINT_QR;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, eventPointQr.getPointName(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				eventPointQr.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (eventPointQrService.updateById(eventPointQr)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}


	/**
     * 修改地点二维码
     */
    @ApiOperation("修改地点二维码")
    @PreAuthorize("@ss.hasPermi('module:eventPointQr:edit')")
    @Log(title = "地点二维码", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventPointQr eventPointQr) {
        return toAjax(eventPointQrService.updateById(eventPointQr) ? 1 : 0);
    }

    /**
     * 删除地点二维码
     */
    @ApiOperation("删除地点二维码")
    @PreAuthorize("@ss.hasPermi('module:eventPointQr:remove')")
    @Log(title = "地点二维码" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(eventPointQrService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
